package tutorial.lite_mod.store_count;


import com.alipay.api.domain.GoodInfo;
import com.example.SpecialApplicationAfter4Example;
import com.example.SpecialApplicationBefore4Example;
import com.wholefarm.model.SpecailApplicationInterface;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.Transaction;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.apache.log4j.Logger;
import public_util.dao.PublicGoodsInfoMapper;
import public_util.database.ConnectionFactory;
import public_util.model.*;
import public_util.servlet.ServletParent;
import public_util.tool_4_handle.Tool_4_Servlet;
import system_api_4_trade.DuzikaiSpecialApplicationFactory;
import system_api_4_trade.SpecialApplicationAfter;
import system_api_4_trade.SpecialApplicationBefore;
import system_api_4_trade.dao.ApiPublicMiddleTableMapper;
import system_api_4_trade.util.sql.SelectTool;
import system_api_4_trade.util.tool_4_handle.DateToolApi;
import system_api_4_trade.util.tool_4_handle.StringToolApi;
import system_api_4_trade.util.tool_4_handle.Tool_4_ServletApi;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


class Tutorial4LiteModTool {

    private static Logger logger = Logger.getLogger(Tutorial4LiteModTool.class);





    /**
     *  修改排班数据
     */
    public static ReturnData batch_add_store_info(SqlSessionFactory sqlSession, ServletParent thisParent, HttpSession hsession, HttpServletResponse response, HttpServletRequest request){

        logger.info("----batch_add_store_info----");
        ReturnData resultData = new ReturnData();
        PublicDataAdminUser adminUser = (PublicDataAdminUser) Tool_4_ServletApi.getAttribute(null, hsession, Const4PublicDataBase.MEM_4_self_public_data_admin_user);
        PublicAgentInfo agentInfo = (PublicAgentInfo)Tool_4_ServletApi.getAttribute(null, hsession,Const4PublicDataBase.MEM_4_self_public_agent_info);
        resultData = Tool_4_ServletApi.checkAccessType(hsession, resultData, 102);
        if (resultData.getStatus() != 0)
        {
            return resultData;
        }

        String id_admin = "-1";

        if (agentInfo != null)
        {
            id_admin = agentInfo.getId_public_data_admin_user() + "";
        }

        if (adminUser != null)
        {
            id_admin = adminUser.getId_public_data_admin_user() + "";
        }

        String id_public_agent_info = request.getParameter(Const4PublicDataBase.PARA_id_public_agent_info);
        id_public_agent_info = StringToolApi.paraHttpFilter(id_public_agent_info);
        if (id_public_agent_info == null)
        {
            resultData.setMsg("id_public_agent_info未传入");
            return resultData;
        }


        String user_name = request.getParameter("user_name");
        if (user_name == null)
        {
            resultData.setMsg("user_name-数据未传入");
            return resultData;
        }

        String goods_info_data = request.getParameter("goods_info_data");
        if (goods_info_data == null)
        {
            resultData.setMsg("goods_info_data-数据未传入");
            return resultData;
        }

        String goodsInfo[] = goods_info_data.split(";");


        List<PublicGoodsInfo> goodsInfoList = new ArrayList<>();
        for ( int i = 0; i < goodsInfo.length; i++)
        {
            String signle_str_4_goods = goodsInfo[i];
            String arrys[] = signle_str_4_goods.split("-_-");
            if (arrys.length != 4)
            {
                continue;
            }
            try
            {
                PublicGoodsInfo newItem4Goods = new PublicGoodsInfo();
                newItem4Goods.setId_public_goods_info(Integer.valueOf(arrys[0]));
                newItem4Goods.setGoods_name(arrys[1]);
                newItem4Goods.setSupply_lock_count(Float.valueOf(arrys[2]));
                newItem4Goods.setSupply_left_count(Float.valueOf(arrys[3]));
                goodsInfoList.add(newItem4Goods);
            }catch(Exception e)
            {
                logger.info(signle_str_4_goods + "====error--" + e);
                continue;
            }
        }


        SqlSession session = sqlSession.openSession();
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Transaction newTransaction = transactionFactory.newTransaction(session.getConnection(), false);
        ApiPublicMiddleTableMapper mMapper = session.getMapper(ApiPublicMiddleTableMapper.class);
        Tutorial4LiteModMapper liteModMapper = session.getMapper(Tutorial4LiteModMapper.class);
        try {
            List<PublicMiddleTable> list4MiddleTable = new ArrayList<>();
            List<PublicGoodsSupply4Agent> list4Supply = new ArrayList<>();
            int id_agent = Integer.valueOf(id_public_agent_info);
            findBath4GoodsSupplyUpdate(user_name, id_agent, list4MiddleTable,list4Supply, goodsInfoList);
            liteModMapper.bachInsert2table(list4MiddleTable);
            session.commit();
            resultData.setStatus(0);
            return resultData;
        }
        catch(Exception e)
        {
            try {
                newTransaction.rollback();
                String msg = Tool_4_ServletApi.showStackTrace(e);
                resultData.setMsg(msg);
                return resultData;

            } catch (SQLException e1) {
                String msg = Tool_4_ServletApi.showStackTrace(e);
                resultData.setMsg(msg);
                return resultData;
            }
        }
        finally
        {
            session.close();
        }
    }



    private static void findBath4GoodsSupplyUpdate(String user_name, int id_public_agent_info,  List<PublicMiddleTable> updateMiddleList,List<PublicGoodsSupply4Agent> updateAgentList,List<PublicGoodsInfo> listData)
    {
        Date process_day = new Date();
        //按照时间来生成
        //当天的安排
        for (int i = 0; i < listData.size(); i++)
        {
            PublicGoodsInfo sigleGoods = listData.get(i);
            PublicMiddleTable item4Middle = new PublicMiddleTable();

            item4Middle.setType_middle_app(23001);
            item4Middle.setType_inner_app(1001);
            item4Middle.setMid_table_remark_049(user_name);
            item4Middle.setIs_online("0");
            item4Middle.setMid_table_remark_001(sigleGoods.getGoods_name());
            item4Middle.setId_public_goods_info(sigleGoods.getId_public_goods_info());
            item4Middle.setMid_table_remark_040(DateToolApi.format(process_day, "yyyyMMdd"));//年月日
            item4Middle.setMid_table_remark_041(DateToolApi.format(process_day, "yyyyMM"));//年月
            item4Middle.setMid_table_remark_042(DateToolApi.format(process_day, "yyyy"));//年
            item4Middle.setTime_insert(new Date());
            item4Middle.setTime_update(new Date());
            item4Middle.setTime_4_begin(process_day);
            item4Middle.setId_public_data_admin_user(800);
            updateMiddleList.add(item4Middle);



            //供应商的信息, 方便批量更新
            PublicGoodsSupply4Agent item4Supply = new PublicGoodsSupply4Agent();
            item4Supply.setId_public_goods_info(sigleGoods.getId_public_goods_info());
            item4Supply.setSeller_id(id_public_agent_info);
            item4Supply.setSupply_left_count(sigleGoods.getSupply_left_count());
            updateAgentList.add(item4Supply);
        }
    }



    public static void main(String[] args) throws Exception {

        /**
         * 验证supply的批量更新, 后面像加入购物车的操作,就会变得比较简单
         */
        SpecialApplicationBefore beforeApp = new SpecialApplicationBefore4Example();
        //本地环境
        beforeApp.setConfiguartion_environment(new String[]{SpecailApplicationInterface.LOAD_CONF_TYPE_FROM_DB, "1021"});
        /*按照独自开重构思路, 进行相关的特殊处理的方法*/
        SpecialApplicationAfter afterApp = new SpecialApplicationAfter4Example();
        DuzikaiSpecialApplicationFactory.setInitApplication(beforeApp, afterApp);
        SqlSessionFactory sqlSession = ConnectionFactory.getSession();
        SqlSession session = sqlSession.openSession();
        try
        {
            Tutorial4LiteModMapper t4lMapper = session.getMapper(Tutorial4LiteModMapper.class);
            List<PublicGoodsInfo> publicGoodsInfos = new ArrayList<>();

            PublicGoodsInfo g1 = new PublicGoodsInfo();
            g1.setId_public_goods_info(160);
            g1.setSupply_left_count(1600);
            g1.setId_public_agent_info(300098);

            PublicGoodsInfo g2 = new PublicGoodsInfo();
            g2.setId_public_goods_info(165);
            g2.setSupply_left_count(16500);
            g2.setId_public_agent_info(300098);
            publicGoodsInfos.add(g1);
            publicGoodsInfos.add(g2);
            t4lMapper.bachupdate2supply(publicGoodsInfos);
            session.commit();
        }
        catch(Exception e)
        {
            Tool_4_Servlet.showStackTrace(e);
            logger.info(e);
        }
        finally
        {
            session.close();
        }
    }

}